package com.woyao;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.ContactSummary;
import com.woyao.core.model.GetSearchResponse;
import com.woyao.core.model.SearchItem;
import com.woyao.core.model.SearchResult;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class ContactsActivity extends AppCompatActivity {
    ProgressDialog progressDialog;


    private List<SearchItem> chanceItems = new ArrayList<SearchItem>();
    private SearchAdapter chanceAdapter;
    private RecyclerView chanceList = null;
    LinearLayoutManager chanceLayoutManager = null;

    private ContentResolver cr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);

        Toolbar toolbar = (Toolbar) findViewById(R.id.id_contacts_toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        chanceList = (RecyclerView)findViewById(R.id.id_contacts_activities_list);
        chanceLayoutManager = new LinearLayoutManager(ContactsActivity.this);
        chanceLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        chanceList.setLayoutManager(chanceLayoutManager);
        chanceList.addItemDecoration(new DividerItemDecoration(ContactsActivity.this, DividerItemDecoration.VERTICAL_LIST));


        this.setTitle("朋友圈");

        tryGetContacts();
    }


    public  void tryGetContacts() {

        if (ContextCompat.checkSelfPermission(ContactsActivity.this,android.Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions( ContactsActivity.this,
                    new String[]{android.Manifest.permission.READ_CONTACTS},
                    1);
            Log.i("woyaooo","'授权了吗？'");
        }else{
            getContacts();
        }


    }

    private void getContacts() {

        ArrayList<String> dups = new ArrayList<String>();
        try {

            cr = getContentResolver();
//            Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            Cursor cs = null;

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                cs = cr.query(uri, null, null, null,  "sort_key", null);
                StringBuilder sb = new StringBuilder();
                while (cs.moveToNext()) {
                    try {
                        //拿到联系人id 跟name
                        int id = cs.getInt(cs.getColumnIndex("_id"));

                        String number = cs.getString(cs.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        number = number.replace(" ","").replace("+86","");

                        if (dups.contains( number ) ){
                            continue;
                        }
                        dups.add(number);
                        String name = cs.getString(cs.getColumnIndex("display_name"));



                        ContactSummary one = new ContactSummary();
                        one.setId(number);
                        one.setTitle(name  );
                        one.setDescription(number);

                        sb.append("displayname:" + name + ";");
                        sb.append("phone:" + number + ";");
                        sb.append("#");

                    }catch (Exception e){
                        Log.i("woyaooo", e.getMessage());
                    }
                }
//                renderThem(true);
                saveReload( sb.toString()) ;
//                Common.setProfileAttr("contacts", sb.toString());

            }

        }catch (Exception e){
            Toast.makeText(this,"不能访问通讯录", Toast.LENGTH_SHORT).show();
        }
    }


    public   void saveReload( final String content){
        progressDialog = new ProgressDialog(ContactsActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在加载朋友信息······");
        progressDialog.show();
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setProfileAttr(WoyaoooApplication.userId,"contacts",content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                progressDialog.dismiss();
                if (success) {
                    search(  );
                } else {

                }
            }

            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);

    }


    public void search(  ){
        progressDialog = new ProgressDialog(ContactsActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在加载朋友信息···");
        progressDialog.show();


        AsyncTask<Void,Void, GetSearchResponse> task1 =new AsyncTask<Void, Void, GetSearchResponse>() {
            @Override
            protected GetSearchResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetSearchResponse> responseCall = svc.search(userId,"chance","friends" );
                try {
                    GetSearchResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetSearchResponse response) {
                progressDialog.dismiss();
                render(response);

            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task1.execute((Void)null);
    }
    private void render(GetSearchResponse response) {
        SearchResult sr = response.getContent();

        if (sr.getChances().size() > 0) {
            chanceItems = sr.getChances();

            chanceAdapter = new SearchAdapter(ContactsActivity.this, chanceItems, "chance");

            chanceAdapter.setChangedHandler(new SearchAdapter.Changed() {
                @Override
                public void view(SearchItem cs) {
                    if (cs.getId() > 0) {
                        Intent intent = new Intent();
                        intent.setClass(ContactsActivity.this, ChanceViewActivity.class);
                        intent.putExtra("id", cs.getId());   //bid
                        startActivity(intent);
                    } else {
//                        Common.alert(SearchActivity.this,"该用户未注册");
                    }
                }

                @Override
                public void act(SearchItem cs) {

                }
            });

            chanceList.setAdapter(chanceAdapter);

        }
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {    // 1 for location
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.i("woyaooo","'已经授权'");
                    getContacts();

                } else {
                    search();
                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }


}
